package ServletMerchant;

import Dao.MctDao;
import Entity.Merchant;
import Util.Page;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "ServletMctDel", value = "/mctdel")
public class ServletMctDel extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        String username = request.getParameter("username");
        try {
            MctDao.del(id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        String loc = request.getParameter("loc");
//        System.out.println(loc);

        request.setAttribute("username",username);
        List<Merchant> list = null;
        try {
            list = MctDao.queryByKey("",username);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        if(loc.equals("update")){
            if(list.size()==0) request.getRequestDispatcher("merchant").forward(request, response);
            else{
                Merchant merchant =list.get(0);

                request.setAttribute("merchant", merchant);
                request.setAttribute("list",list);
                //获取页码
                int pagenum = 1,total = list.size();
                pagenum = Integer.parseInt(request.getParameter("pagenum"));
                Page page = new Page(pagenum,total);
                request.setAttribute("page",page);
//        System.out.println("get:"+page);

                request.getRequestDispatcher("mctupdate.jsp?username="+username).forward(request, response);
            }
        }
        else{
            //获取页码
            int pagenum = 1,total = list.size();
            pagenum = Integer.parseInt(request.getParameter("pagenum"));
            Page page = new Page(pagenum,total);
            request.setAttribute("page",page);
//        System.out.println("get:"+page);

            request.setAttribute("list",list);
            response.sendRedirect("merchant?username="+username);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
